package com.example.supermarket_back.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.example.supermarket_back.config.cache.CacheConfig;
import com.example.supermarket_back.dao.RegisterDao;
import com.example.supermarket_back.entity.ToEmail;
import com.example.supermarket_back.entity.User;
import com.example.supermarket_back.service.RegisterService;
import com.example.supermarket_back.utils.CommonUtil;
import com.example.supermarket_back.utils.constants.ErrorEnum;
import com.example.supermarket_back.utils.email.Email;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class RegisterImpl implements RegisterService {

    @Resource
    private RegisterDao registerDao;

    @Resource
    private CacheConfig cacheConfig;

    @Resource
    private Email email;

    //发送注册验证码邮件
    @Override
    public JSONObject sendCaptcha(String str_email) {
        ToEmail toEmail=new ToEmail(str_email,"注册/登陆验证码");
        boolean successFlag= email.sendEmailVerificationCode(toEmail);
        return successFlag?CommonUtil.successJson("发送成功！请注意查收邮箱验证码"):
                CommonUtil.errorJson(ErrorEnum.E_504);
    }


    @Override
    public JSONObject registerForm(String email, String password, String captcha) {
        User user=new User(password,email);
        //检查redis中是否存该邮箱对应得未过期验证码
        boolean exitKey=cacheConfig.exists(email);
        //0 已存在账户 1 注册成功
        int res=0;
        String username;
        if(!exitKey){
           return CommonUtil.errorJson(ErrorEnum.E_402);
        }else if(!Objects.equals(captcha, cacheConfig.getData(email))){//验证验证码一致性
            return CommonUtil.errorJson(ErrorEnum.E_410);
        }else{
            //插入数据库
            res=registerDao.register(user);
            //得到自增的用户名
            username=String.valueOf(user.getUsername());
            cacheConfig.deleteKey(email);
        }
        return res==1?CommonUtil.successJson(username):CommonUtil.errorJson(ErrorEnum.E_406);
    }
}
